﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Tracy.CoreLib.Data;
using Tracy.CoreLib;
using System.IO;
using Tracy.Engine;
using CoreLib.Message;
using System.Collections.ObjectModel;

namespace Tracy
{
    public partial class FormFilter : AbstractMessageHandlerForm
    {
        private bool changed = false;
        public bool Changed
        {
            get { return changed; }
        }
        private TracyEngine tracyEngine = null;
        private RssFilter newFilter = null;
        public RssFilter NewFilter
        {
            get { return newFilter; }
        }

        private Collection<RssFeedSource> _sourcesToAdd;
        /// <summary>
        /// 需要添加为Tag的源
        /// </summary>
        public Collection<RssFeedSource> SourcesToAdd
        {
            get { return _sourcesToAdd; }
        }

        private Collection<RssFeedSource> _sourcesToRemove;
        /// <summary>
        /// 需要从Tag中移除的源
        /// </summary>
        public Collection<RssFeedSource> SourcesToRemove
        {
            get { return _sourcesToRemove; }
        }

        public FormFilter(TracyEngine engine)
        {
            InitializeComponent();
            this.tracyEngine = engine;
            LoadFeedSourceList();
        }

        public FormFilter(TracyEngine engine, RssFilter oldFilter)
        {
            InitializeComponent();
            newFilter = oldFilter;
            this.tracyEngine = engine;
            LoadFeedSourceList();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (textBoxDir.Text == "")
            {
                MessageBox.Show("保存位置不可为空！");
                return;
            }
            if (changed)
            {

                newFilter = new RssFilter();
                newFilter.Title = textBoxTitle.Text;
                newFilter.Description = textBoxDescription.Text;
                newFilter.Folder = textBoxDir.Text;
                newFilter.Filter = new Filter();
                newFilter.Filter.FilterExpr = textBoxExpr.Text;

                SaveRssFeedList();

                this.DialogResult = DialogResult.OK;
            }
            this.Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {

        }

        private void FormFilter_Load(object sender, EventArgs e)
        {
            tracyEngine.OnMessageProcessed += new EventHandler<TracyMessageEventArgs>(tracyEngine_OnMessageProcessed);
            if (newFilter != null)
            {
                textBoxTitle.Text = newFilter.Title;
                textBoxDescription.Text = newFilter.Description;
                textBoxDir.Text = newFilter.Folder;
                textBoxExpr.Text = newFilter.Filter.FilterExpr;
                buttonOK.Enabled = true;
                changed = false;
            }
            else
            {
                changed = true;
            }

            
        }

        public void SetDefaultSource(RssFeedSource source)
        {
            listBoxSourceAssigned.Items.Add(source);
            if (listBoxSourceToAssign.Items.Contains(source))
            {
                listBoxSourceToAssign.Items.Remove(source);
            }
        }

        private void LoadFeedSourceList()
        {
            //加载FeedSource
            foreach(RssFeedSource source in tracyEngine.GetRssSources()){
                listBoxSourceToAssign.Items.Add(source);
            }

            //已关联的FeedSource
            if (newFilter != null)
            {
                foreach (RssFeedSource source in tracyEngine.Bus.TracyTagManager.GetTaggedTargets(newFilter, Constants.CONST_DATA_TYPE_RSSFEEDSOURCE))
                {
                    listBoxSourceAssigned.Items.Add(source);
                    listBoxSourceToAssign.Items.Remove(source);
                }
            }
        }

        private void SaveRssFeedList()
        {
            //计算需要添加/移除的Tag
            _sourcesToAdd = new Collection<RssFeedSource>();
            _sourcesToRemove = new Collection<RssFeedSource>();

            foreach (RssFeedSource source in listBoxSourceAssigned.Items)
                _sourcesToAdd.Add(source);

            foreach (RssFeedSource source in tracyEngine.Bus.TracyTagManager.GetTaggedTargets(newFilter, Constants.CONST_DATA_TYPE_RSSFEEDSOURCE))
                _sourcesToRemove.Add(source);
                
            foreach (RssFeedSource source in listBoxSourceAssigned.Items)
                if (_sourcesToRemove.Contains(source)) _sourcesToRemove.Remove(source);

            foreach (RssFeedSource source in tracyEngine.Bus.TracyTagManager.GetTaggedTargets(newFilter, Constants.CONST_DATA_TYPE_RSSFEEDSOURCE))
                if (_sourcesToAdd.Contains(source)) _sourcesToAdd.Remove(source);


        }

        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            if (textBoxDir.Text != "")
            {
                filterFolderBrowserDialog.SelectedPath = textBoxDir.Text;
            }
            if (filterFolderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxDir.Text = filterFolderBrowserDialog.SelectedPath;
            }
        }

        private void textBoxTitle_TextChanged(object sender, EventArgs e)
        {
            changed = true;
        }

        private void textBoxDescription_TextChanged(object sender, EventArgs e)
        {
            changed = true;
        }

        private void textBoxDir_TextChanged(object sender, EventArgs e)
        {
            changed = true;
        }

        private void textBoxExpr_TextChanged(object sender, EventArgs e)
        {
            changed = true;
        }

        private void buttonTest_Click(object sender, EventArgs e)
        {
            //先更新源，之后由EndUpdateFeed()来处理
            tracyEngine.MessageGenerator.UpdateFeed(this);
            buttonTest.Enabled = false;

        }

        protected override void EndProcessMessage(ITracyMessage msg)
        {
            if (msg.Sender == this)//由本窗体发出的消息
            {
                if (msg is UpdateFeedMessage) EndUpdateFeed();
            }
        }

        /// <summary>
        /// 源已更新
        /// </summary>
        private void EndUpdateFeed()
        {
            RssFilter tmpFilter = new RssFilter();
            tmpFilter.Filter = new Filter();
            tmpFilter.Filter.FilterExpr = textBoxExpr.Text;
            StringWriter sw = new StringWriter();

            IManagedXmlModelCollection testSourceList = new ManagedXmlModelCollection();
            foreach (RssFeedSource source in listBoxSourceAssigned.Items) testSourceList.Add(source);

            foreach (ResourceItem item in tracyEngine.ExecuteFilter(tmpFilter, testSourceList))
            {
                if (item != null) sw.WriteLine(item.Title);
            }
            string msg = sw.ToString();
            if (msg == "")
            {
                MessageBox.Show(Constants.CONST_MOE_MESSAGE_EMPTYRESULT);
            }
            else
            {
                MessageBox.Show(msg);
            }
            buttonTest.Enabled = true;
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            RssFeedSource[] selected = new RssFeedSource[listBoxSourceToAssign.SelectedItems.Count];
            listBoxSourceToAssign.SelectedItems.CopyTo(selected, 0);
            foreach (RssFeedSource source in selected)
            {
                listBoxSourceAssigned.Items.Add(source);
                listBoxSourceToAssign.Items.Remove(source);
            }
            changed = true;
        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            RssFeedSource[] selected = new RssFeedSource[listBoxSourceAssigned.SelectedItems.Count];
            listBoxSourceAssigned.SelectedItems.CopyTo(selected, 0);
            foreach (RssFeedSource source in selected )
            {
                listBoxSourceAssigned.Items.Remove(source);
                listBoxSourceToAssign.Items.Add(source);
            }
            changed = true;
        }
    }
}
